package com.fastmobile.impl;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.json.JSONException;
import org.json.JSONObject;

import com.fastmobile.dao.InvoiceReferenceDao;
import com.fastmobile.entity.InvoiceReference;

public class InvoiceReferenceImpl implements InvoiceReferenceDao{
	protected EntityManager em;
	
	public EntityManager getEntityManager() {
		return em;
	}
	
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}

	@Override
	public InvoiceReference getInvoiceReferenceById(String id) {
		return getEntityManager().find(InvoiceReference.class, id);
	}

	@Override
	public void unlockInvoice(String id, Date date, String reason) {
		InvoiceReference invoice = getInvoiceReferenceById(id);
		DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
		String note = "";
		if (invoice.getNotes() != null) {
			note = invoice.getNotes();
		}
		note = note + " Unlock " + reason + " - " + df.format(date);
		em.getTransaction().begin();
		invoice.setInvLock(Boolean.FALSE);
		invoice.setInvUnlock(Boolean.TRUE);
		invoice.setNotes(note);
		invoice.setDateOfLock(date);
		em.getTransaction().commit();
	}
	
	@Override
	public void lockInvoice(String id, Date date, String reason) {
		InvoiceReference invoice = getInvoiceReferenceById(id);
		DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
		String note = "";
		if (invoice.getNotes() != null) {
			note = invoice.getNotes();
		}
		note = note + " Lock " + reason + " - " + df.format(date);
		em.getTransaction().begin();
		invoice.setInvLock(Boolean.TRUE);
		invoice.setInvUnlock(Boolean.FALSE);
		invoice.setNotes(note);
		invoice.setDateOfLock(date);
		em.getTransaction().commit();
	}
}
